/**
 * @created by kongqf on 2019-12-5 09:36:02
 * @updated by
 * @description jobFlowGraph
 */
// 注意js引用顺序
define([
  './pages/use/apps/jobManager/jobFlowGraph/jobFlowGraph.css',
  './libs/mxgraph/libs/init.js',
  './libs/mxgraph/libs/sanitizer.min.js',
  './libs/mxgraph/libs/editorUi.js',
  './libs/mxgraph/libs/editor.js',
  './libs/mxgraph/libs/sidebar.js',
  './libs/mxgraph/libs/graph.js',
  './libs/mxgraph/libs/format.js',
  './libs/mxgraph/libs/shapes.js',
  './libs/mxgraph/libs/actions.js',
  './libs/mxgraph/libs/menus.js',
  './libs/mxgraph/libs/toolbar.js',
  './libs/mxgraph/libs/dialogs.js',
  './custom/widgets/js/YuWorkflow.js',
  'pages/use/monitors/globalMonitor/globalMonitor.css',
],function (require, exports) {
  /**
   * 页面加载完成时触发
   * @param hashCode 路由ID
   * @param data 传递数据对象
   * @param cite 页面站点信息
   */
  exports.ready = function (hashCode, data, cite) {
    data = {
      appCode: 'YU',
      groupCode: 'bb'
    }
    yufp.lookup.reg('USE_TASK_JOB_TYPE,USE_JOB_RUN_STATE');
    var size = yufp.frame.size();
    yufp.custom.vue({
      el: cite.el,
      data: function () {
        return {
          timeOptions: [{key: -1, value:'不自动刷新'},{key: 10, value:'10秒'},{key: 20, value:'20秒'},{key: 30, value:'30秒'},{key: 60, value:'60秒'}],
          frequencyOptions: [],
          height: size.height - 58,
          width: size.width,
          timerDelay: 60,
          system: '',
          currentTime: yufp.util.dateFormat(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
          dialogVisible:false,
          dialogTitle: '',
          formDisabled: false,
          circulationFormData:{},
          workBaseFormData:{},
          workExecFormData: {},
          workAdditionalFormData: {},
          workData: {},
          timer: null,
          filterText: '',
          options: [{
            key: 'Y',
            value: '是'
          },{
            key: 'N',
            value: '否'
          }],
          nodetype: '',
          sidebarItems: [],
          tableData1: [],
          data: [
            { id: '0', label: '根节点', pid: '-1' },
            { id: '1', label: '1-1', pid: '0' },
            { id: '2', label: '1-2', pid: '0' },
            { id: '3', label: '1-3', pid: '0' },
            { id: '4', label: '1-1-1', pid: '1' },
            { id: '5', label: '1-1-2', pid: '1' },
            { id: '6', label: '1-2-1', pid: '2' },
            { id: '7', label: '1-2-2', pid: '2' },
            { id: '8', label: '1-3-1', pid: '3' },
            { id: '9', label: '三级-1-1-1', pid: '4' }
          ],
          monitorInfoFormdata:{}
        };
      },
      mounted(){
        // 获取应用系统下拉列表数据
        this.getFrequencyOptions();
      },
      methods: {
        // 获取应用系统下拉列表数据
        getFrequencyOptions:function(){
          var _this = this;
          _this.frequencyOptions.splice(0);
          yufp.service.request({
            url: backend.useService + '/plats/apps/getWftAppList',
            method: 'get',
            callback: function (code, message, response) {
              response.data.forEach(item=>{
                var obj={};
                obj.key=item.appCode;
                obj.value=item.appName;
                _this.frequencyOptions.push(obj);
              })
              _this.system = _this.frequencyOptions.length > 0 ? _this.frequencyOptions[0].value : '';
            }
          });
        }, 
        initGraph:function(){
          var _this = this;
          yufp.service.request({
            url: backend.useService + '/monitor/centerMonitor/queryCenterFlowChart',
            method: 'get',
            data: {
              appCode: _this.system
            },
            callback: function (code, message, response) {
              if(response && response.data) {
                console.log('流程数据', response)
                var notSetEdgeAnchorPoint = response.data.newFlag == 1;
                yufp.clone(response.data,_this.monitorInfoFormdata);
                _this.$refs.refWorkflow.clearGraph();
                var vertexList = _this.$refs.refWorkflow.addVertexList(null, _this.data2CellData(response.data.flowJobInfoList, response.data));
                _this.$refs.refWorkflow.addEdgeList(null, _this.data2EdgeData(response.data.flowLinksInfoList), notSetEdgeAnchorPoint, vertexList);
                _this.$refs.refWorkflow.updateWorkStates([], _this.data2CellData(response.data.flowJobInfoList, response.data));
              } else {
                _this.$refs.refWorkflow.clearGraph();
              }
              _this.currentTime = yufp.util.dateFormat(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
              if (yufp.frame.getTab().title === '集中监控') {
                _this.$message('刷新成功');
              }
              _this.$refs.refWorkflow.graphComplete();
            }
          });
        },
        getData2Form: function(data){
          this.workBaseFormData = yufp.extend(true, data, {
           appCode: '',
            typeCode: '',
            actionCode: '',
            actionName: '',
            maxRetry: '',
            actionPrior: '',
            redcheckbox: '',
            redselect: '',
            intrFlag: '',
            multiFlag: '',
            remark: ''
          });
          console.log('表单数据', this.workBaseFormData );
        },
        /**
         * 将接口数据转换成graph节点数据
         */
        data2CellData: function(data, workData){
          var cells = [];
          var baseY = 160;
          if(data && data.length>0){
            baseY = data[0].positionY
          }
          // 添加开始结束节点
          cells.push({
            id: 'start',
            nodetype: 'start',
            value: '',
            x: workData.posBeginX || -100,
            y: workData.posBeginY || baseY,
            width: 50,
            height: 50,
            style: 'image;image=libs/mxgraph/images/workflow/wstart.png;',
            relative: false,
            data: {}
          });
          data.forEach(function(item){
            cells.push({
              id: item.actionCode,
              nodetype: item.typeCode,
              value: item.actionCode,
              x: item.positionX,
              y: item.positionY,
              width: 50,
              height: 50,
              style: 'image;image=libs/mxgraph/images/workflow/'+ item.typeCode +'.png;',
              relative: false,
              data: item
            })
          })
          cells.push({
            id: 'end',
            nodetype: 'end',
            value: '',
            x: workData.posEndX || (cells.length === 1 ? 400 : cells[cells.length-1].x + 200),
            y: workData.posEndY || baseY,
            width: 50,
            height: 50,
            style: 'image;image=libs/mxgraph/images/workflow/wend.png;',
            relative: false,
            data: {}
          });
          return cells;
          // var cells = [];
          // data.forEach(function(item){
          //   cells.push({
          //     id: item.actionCode,
          //     nodetype: item.typeCode,
          //     value: item.actionCode,
          //     x: item.positionX * 4 / 3,
          //     y: item.positionY * 4 / 3,
          //     width: 50,
          //     height: 50,
          //     style: 'image;image=libs/mxgraph/images/wstart.png;',
          //     relative: false,
          //     data: item
          //   })
          // })
          // return cells;
        },
        data2EdgeData: function(data){
          var cells = [];
          data.forEach(function(item){
            cells.push({
              id: (item.actionCode.trim() || 'start') + '-' + (item.condAction.trim() || 'end'),
              value: '',
              path: item.flowPath,
              style: item.drawInfo || '',
              source: item.actionCode.trim() || 'start',
              target: item.condAction.trim() || 'end'
            })
          })
          return cells;
        },
        getSidebarItems:function(){
          var items = [
            { img: 'w1', title: '步骤', data: { nodetype: 'C' }},
            { img: 'w2', title: '步骤结束', data: { nodetype: 'C' }},
            { img: 'w3', title: '步骤开始', data: { nodetype: 'C' }},
            { img: 'w4', title: '创建对象组件', data: { nodetype: 'C' }},
            { img: 'w5', title: '单选', data: { nodetype: 'C' }},
            { img: 'w6', title: '赋值', data: { nodetype: 'C' }},
            { img: 'w7', title: '赋值SQL', data: { nodetype: 'C' }},
          ];
          this.$refs.refWorkflow.setSidebar(items);
        },
        frequencyChangeFn:function(){
          var _this = this;
          yufp.service.request({
            url: backend.useService + '/monitor/centerMonitor/queryCenterFlowChart',
            method: 'get',
            data: {
              appCode: _this.system
            },
            callback: function (code, message, response) {
              if(response && response.data) {
                console.log('流程数据', response);
                var notSetEdgeAnchorPoint = response.data.newFlag == 1;
                _this.setRefreshTimer();
                yufp.clone(response.data,_this.monitorInfoFormdata);
                _this.$refs.refWorkflow.clearGraph();
                var vertexList = _this.$refs.refWorkflow.addVertexList(null, _this.data2CellData(response.data.flowJobInfoList, response.data));
                _this.$refs.refWorkflow.addEdgeList(null, _this.data2EdgeData(response.data.flowLinksInfoList), notSetEdgeAnchorPoint, vertexList);
                _this.$refs.refWorkflow.updateWorkStates([], _this.data2CellData(response.data.flowJobInfoList, response.data));
              } else {
                _this.$refs.refWorkflow.clearGraph();
              }
              _this.currentTime = yufp.util.dateFormat(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
              _this.$refs.refWorkflow.graphComplete();
            }
          });
        },
        setRefreshTimer: function(){
          var _this = this;
          _this.timer && window.clearInterval(_this.timer);
          if (_this.timerDelay > 0) {
            _this.timer = setInterval(function(){
              _this.btnRefreshWorkFlowFn();
            }, parseInt(_this.timerDelay) * 1000)
          }
        },
        btnRefreshWorkFlowFn:function(){
          this.btnUpdateWorkFlowFn();
        },
        btnUpdateWorkFlowFn: function(){
          this.initGraph();
        },
        celldblclickFn: function (cell) {
          var _this = this;
          var data = yufp.clone(cell.data, {});
          var requestUrl = '';
          if (cell.data.hisFlag === '1') {
            data.isHistory = true;
            requestUrl = '/monitor/taskMonitorHis/queryFlowChart';
          } else {
            requestUrl = '/monitor/taskMonitor/queryFlowChart';
          }
          yufp.service.request({
            url: backend.useService + requestUrl,
            method: 'get',
            data: {
              coreId: data.coreId,
              cycleNo: data.cycleNo,
              groupCode: data.groupCode,
              appCode: data.appCode
            },
            callback: function (code, message, response) {
              if(!response.data) {
                _this.$message({message: '流程图数据为空！', type: 'warning',duration: 6000});
                return;
              } else {
                _this.nodetype = data.nodetype;
                var customKey = 'custom_' + new Date().getTime();
                var routeId = 'router_' + new Date().getTime();
                var url = 'pages/use/monitors/taskMonitor/taskMonitorGraph/taskMonitorGraph';
                yufp.router.addRoute(routeId, {
                  html: url + '.html',
                  js: url + '.js'
                });
                yufp.frame.addTab({
                  id: routeId, // 菜单功能ID（路由ID）
                  key: customKey, // 自定义唯一页签key,请统一使用custom_前缀开头
                  title: data.actionName + '_流程图', // 页签名称
                  data: yufp.clone({routeId:routeId, isLock: true}, data)// 传递的业务数据，可选配置
                });
              }
            }
          });
        }
      },
      destroyed: function () {
        this.timer && window.clearTimeout(this.timer);
      }
    });
  };

  /**
   * 页面传递消息处理
   * @param type 消息类型
   * @param message 消息内容
   */
  exports.onmessage = function (type, message) {
  };

  /**
   * 页面销毁时触发destroy方法
   * @param id 路由ID
   * @param cite 页面站点信息
   */
  exports.destroy = function (id, cite) {
  };
});
